<?php

class LangAction extends PublicAction
{

    protected $langpath;
    protected $lang;
    protected $langModel;

    function _initialize()
    {
        parent::_initialize();
        $this->langpath = LANG_PATH . LANG_NAME . '/';
        $this->fieldpath = APP_PATH . 'Lib/Field/';
        $this->langModel = D('Lang');
    }

    public function index()
    {
        $list = $this->langModel->select();
        $this->assign('list', $list);

        //记录当前位置
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->display();
    }

    function edit()
    {
        if (IS_POST) {
            if (false === $this->langModel->create()) {
                $this->error($this->langModel->getError());
            }

            if (false !== $this->langModel->save()) {
                saveCache('Lang');
                $this->success('修改成功!', cookie('__forward__'));
            } else {
                $this->success('修改失败!: ' . $this->langModel->getDbError());
            }
        } else {
            $id = I('id', '', 'intval');

            if (empty($id))
                $this->error('缺少必要的参数!');

            $vo = $this->langModel->getById($id);

            $this->assign('vo', $vo);
            $this->display();
        }
    }

    //新增语言
    function add()
    {
        if (IS_POST) {
            $lang_path = LANG_PATH . $_POST['mark'] . '/';
            $r = dir_copy(LANG_PATH . 'cn/', $lang_path);

            if (false === $this->langModel->create()) {
                $this->error($this->langModel->getError());
            }

            $id = $this->langModel->add();

            if ($id !== false) {
                $base_config = include($this->fieldpath . 'config.php');
                foreach ($base_config as $config) {
                    $config['lang'] = $id;
                    M('Config')->add($config);
                }

                saveCache('Lang');
                $this->success('新增成功！', cookie('__forward__'));
            } else {
                $this->error('新增失败！: ' . $this->langModel->getDbError());
            }

        } else {
            $this->display();
        }
    }

    /**
     * 删除
     *
     */
    function delete()
    {
        $id = I('get.id', 0, 'intval');

        if ($id) {
            if (false !== $this->langModel->delete($id)) {
                saveCache('Lang');
                //配置信息
                M('Config')->where('lang=' . $id)->delete();
                $this->success('删除成功！');
            } else {
                $this->error('删除失败！: ' . $this->langModel->getDbError());
            }
        } else {
            $this->error('缺少必要的参数!');
        }
    }

    public function listorder()
    {
        $ids = $_POST['listorders'];

        foreach ($ids as $key => $r) {
            $data['listorder'] = $r;
            $this->langModel->where('id=' . $key)->save($data);
        }

        $this->success('提交成功!');
    }
}